package edu.snake.implement.view;


import edu.snake.core.model.Arena;
import edu.snake.core.model.Character;
import edu.snake.core.model.Character.CharacterName;
import edu.snake.core.model.Position;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import static edu.snake.implement.factory.PositionFactory.getNewPosition;

public class ViewArena extends JPanel implements ActionListener {

    FrogRender frogRender;
    SnakeRender snakeRender;
    EmptyCellRender emptyCellRender;


    public ViewArena(int width, int height) {
        setFocusable(true);
        setPreferredSize(new Dimension(width, height));
        this.frogRender = new FrogRender();
        this.emptyCellRender = new EmptyCellRender();
        this.snakeRender = new SnakeRender();
    }


    public void gameOver() {
        String msg = "Game Over";
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = getFontMetrics(small);
        Graphics g = this.getGraphics();
        g.setColor(Color.white);
        g.setFont(small);
        int stringHalfSize = metr.stringWidth(msg) / 2;
        int width = this.getWidth() / 2 - stringHalfSize;
        int height = this.getHeight() / 2;
        g.drawString(msg, width, height);
    }

    public void actionPerformed(ActionEvent e) {
        Arena arena = (Arena) e.getSource();
        drawArena(arena);
    }

    public void drawArena(Arena arena) {
        //todo draw arena throw Iterator
        int width = arena.getWidth();
        int height = arena.getHeight();
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                Character character = arena.getFromArena(getNewPosition(i, j));
                CharacterName characterName;
                if (character != null) {
                    characterName = character.getName();
                } else {
                    characterName = CharacterName.EMPTY;
                }
                if (characterName.equals(CharacterName.SNAKE)) {
                    snakeRender.render(getNewPosition(i, j), character, this.getGraphics());
                } else if (characterName.equals(CharacterName.FROG)) {
                    frogRender.render(getNewPosition(i, j), character, this.getGraphics());
                } else if (characterName.equals(CharacterName.EMPTY)) {
                    emptyCellRender.render(getNewPosition(i, j), null, this.getGraphics());
                }
            }
        }
    }

}
